<?php
namespace app\common\tool\profit_sharing;

class Multiple extends Base {

	protected function group_buying_user($uid, $spreaCommission, $text) {
        $userOpenidModel = loadModel('tyyh\\UserOpenid');
        $spreadUser = $userOpenidModel->where(['uid' => $uid])->find();
        $receiver = [
            'type'              => 'PERSONAL_OPENID',
            'receiver_account'  => $spreadUser['miniprogramid'],
            'amount'            => $spreaCommission,
            'description'       => $text
        ];
        return $receiver;  
    }

	//多人分佣
    protected function multiple($order, $receivers, $incomeLog) {
        $profitSharingModel = loadModel('jy\\ProfitSharing');
        $result = '';
        try {
            $profitSharingModel->startTrans();
            $psid = $this->save_profit_sharing($order);
            $this->save_profit_sharing_receiver($order, $psid);
            $this->save_income_log($incomeLog);
            if(loadEnum('RouteType')->is_service($order['route'])) { //是否是服务商商户号
            	//服务商商户号分账
                $result = loadTool('profit_sharing\\Service')->share($order, $receivers);
            } else {
            	//特约商户号分账
                $result = loadTool('profit_sharing\\Contributing')->share($order, $receivers);
            }
            $profitSharingModel->commit();
        } catch(\Exception $e) {
            $profitSharingModel->rollback();
            throw $e;
        }
        return $result;
    }

    //保存分账信息
    protected function save_profit_sharing($order) {
        $profitSharingModel = loadModel('jy\\ProfitSharing');
    	$type = loadEnum('ProfitSharingType')->code2key('quaneshangjia');
        $profitSharingModel->save([
            'oid'  => $order['id'],
            'type' => $type,
            'fee'  => $order['total_fee']
        ]);
        return $profitSharingModel->id;
    }

    //保存分账服务信息
    protected function save_profit_sharing_receiver($order, $psid) {
        $profitSharingReceiverModel = loadModel('jy\\ProfitSharingReceiver');
    	$type = loadEnum('ProfitSharingReceiverType')->code2key('shangjia');   
        $profitSharingReceiverModel->save([
            'psid'        => $psid,
            'type'        => $type,
            'account'     => $order['sub_mch_id'],
            'fee'         => $order['total_fee'],
            'description' => '系统分配'
        ]);
    }

    //保存收录记录
    protected function save_income_log($incomeLog) {
    	return loadModel('jy\\IncomeLog')->isUpdate(false)->saveAll($incomeLog);
    }
}
